<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'timeOfEntry', order: 'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ loadformOfEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="账户状态" />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssign(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hdel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 10, 15]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>

      <!-- 准备新增员工的弹层 -->
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hClose">
        <addor-edit ref="addor" @close="showDialog=false" @success="hsuccess" />
      </el-dialog>

      <!-- 准备分配角色的弹层 -->
      <el-dialog
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="roleshowDialog"
        title="分配角色"
      >

        <assignRole v-if="roleshowDialog" :role-id="roleId" @close="roleshowDialog=false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import assignRole from './assignRole.vue'
import addorEdit from './empDialog'
import { getEmployeeList, delEmployee } from '@/api/employee'
import employeeNum from '@/constant/employees'
// 数组方法,取子元素转化value,==>对象方法取键
/* const hireType = {}
employeeNum.hireType.forEach(item => {
  hireType[item.id] = item.value
}) */
// 函数方法转对象,再使用对象新增方法
const hireType = employeeNum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: {
    addorEdit,
    assignRole
  },
  data() {
    return {
      roleId: '', // 分配角色时传入的id
      roleshowDialog: false, // 分配角色的弹层
      showDialog: false, // 弹层的状态
      list: [],
      page: 1, // 页码值
      size: 2, // 每页条数
      total: 0// 总条数
    }
  },
  created() {
    this.getEmployeeList()
    // console.log('枚举的方法', employeeNum)
  },
  methods: {
    // 格式化数据函数
    dataFormate(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const newlist = list[0]
      if (newlist) {
        const theader = Object.keys(newlist).map(item => {
          return mapInfo[item]
        })
        const data = list.map(item => {
          return Object.values(item)
        })
        return { theader, data }
      }
    },
    // 分配角色弹层
    hAssign(id) {
      this.roleId = id
      this.roleshowDialog = true
    },
    // excel导出
    async handleDownload() {
      // 1.调用接口.请求数据
      try {
        const res = await getEmployeeList(this.page, this.size)
        console.log('列表的数据', res)
        if (res.code !== 10000) return
        console.log(res.data.rows)
        // 2.格式化数据 header data
        const { theader, data } = this.dataFormate(res.data.rows)
        // 3.将格式化好的数据写入到excel中
        // import是懒加载的方式
        import('@/vendor/Export2Excel').then(excel => {
        // excel指的是模块对象(文件对象)，就可以直接调用文件中的任何函数或者使用文件中的任何变量  excel.函数名()   || excel.变量
          console.log(excel, 'excel')
          // excel调用export_json_to_excel()
          excel.export_json_to_excel({
            header: theader,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 删除函数
    hdel(id) {
      this.$confirm('你确定要删除吗').then(async() => {
        const res = await delEmployee(id)
        if (res.code !== 10000) return
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.getEmployeeList()
      }).catch((err) => {
        console.log(err)
      })
    },
    // 成功回来的参数
    hsuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.showDialog = false
      this.getEmployeeList()
    },
    // 关闭弹层时会触发的函数
    hClose() {
      this.$refs.addor.resetForm()
      this.showDialog = false
    },
    // 条数改变时触发的函数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.getEmployeeList()
    },
    // 页码值改变时触发的函数
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.getEmployeeList()
    },
    // 获取员工列表触发的函数
    async getEmployeeList() {
      try {
        const data = await getEmployeeList(this.page, this.size)
        console.log('列表的数据', data)
        if (data.code !== 10000) return
        this.list = data.data.rows
        this.total = data.data.total
      } catch (error) {
        console.log(error)
      }
    },
    // 需求返回正式和非正式
    loadformOfEmployment(num) {
      // console.log(typeof (num))
      return hireType[num] || '未知'
    }
  }
}
</script>
